/**
 * Created by legion on 2018/9/13.
 */

(function($, window) {
    "use strict";
    var detail = (function () {
        detail = function (options) {
            this.settings = $.extend({}, $.fn.extend);
            //this.element = element;
            this.init();
        };
        detail.prototype = {
            /*说明：初始化插件*/
            init: function () {
                let self = this;

                this.isBooking = true;

                self.settings.hotelData.hotel_id = api.pageParam.hotelId;

                self.selectors = this.settings.selectors;
                self.header = this.selectors.header;
                self.body = this.selectors.body;
                self.main = this.selectors.mainInfo;
                self.ellist = this.selectors.elList;
                self.arrival = this.selectors.arrival;
                self.departure = this.selectors.departure;

                this._initPage();
                this._dateSelect();
                this._eventBinding();
                this.getInfo();
            },
            //页面初始化
            _initPage: function () {
                let self = this;
                //$('.qt-wrapper').css('top',$(self.header).height());
                //日期
                var arrivalArr = self.settings.hotelData.arrival_date.split('-');
                $(self.arrival).text(arrivalArr[1] + "-" + arrivalArr[2]);

                var departureArr = self.settings.hotelData.departure_date.split('-');
                $(self.departure).text(departureArr[1] + "-" + departureArr[2]);

                let weekArr = self._getWeekNum(self.settings.hotelData.arrival_date, self.settings.hotelData.departure_date);
                // console.log(JSON.stringify(weekArr));

                $(self.arrival).parent().find('i').text(weekArr[0]);
                $(self.departure).parent().find('i').text(weekArr[1]);

                $('.NumDate').text(self.settings.hotelData.date_amount);
            },
            //日期选择
            _dateSelect: function () {
                let self = this;
                let el = $('.time-select');
                el.on('click',function () {
                    $('.mask_calendar').show();
                });
                $('.mask_calendar').on('click',function (e) {
                    if(e.target.className === "mask_calendar"){
                        $('.calendar').slideUp(200);
                        $('.mask_calendar').fadeOut(200);
                    }
                });
                el.calendarSwitch({
                    selectors : {
                        sections : ".calendar"
                    },
                    index : 4,      //展示的月份个数
                    animateFunction : "slideToggle",        //动画效果
                    controlDay:true,//知否控制在daysnumber天之内，这个数值的设置前提是总显示天数大于90天
                    daysnumber : "90",     //控制天数
                    comeColor : "#2EB6A8",       //入住颜色
                    outColor : "#2EB6A8",      //离店颜色
                    comeoutColor : "#E0F4F2",        //入住和离店之间的颜色
                    callback :function(startDate, endDate){//回调函数
                        $('.mask_calendar').fadeOut(200);
                        var NumDate = $('.NumDate').text();    //共多少晚

                        if (parseInt(self.settings.hotelPolicy.order_type) !== -1) {
                            var startDateArr = startDate.split('-');
                            var startStr = parseInt(startDateArr.join(''));

                            var compareArr = self.settings.hotelData.travelTimer.split('/');
                            var compareStr = parseInt(compareArr.join(''));

                            if(startStr < compareStr) {
                                $toast("选择的出行日期小于申请单日期!");
                                self.isBooking = false;
                                return false;
                            } else {
                                self.isBooking = true;
                            }
                        }
                        // console.log(startDate);
                        self.settings.hotelData.arrival_date   = startDate;
                        self.settings.hotelData.departure_date = endDate;
                        self.settings.hotelData.date_amount    = NumDate;
                        // console.log($(self.arrival).parent().find('i').text());
                        $(self.arrival).parent().find('i').append('入住');
                        $(self.departure).parent().find('i').append('离店');

                        $api.setStorage('hotel_data', JSON.stringify(self.settings.hotelData));

                        self.getInfo();
                        api.sendEvent({
                            name: 'listFrmTimeEvt'
                        });
                    },
                    comfireBtn:'.comfire'//确定按钮的class或者id
                });
            },
            //事件绑定
            _eventBinding: function () {
                let self = this;

                window.addEventListener('scroll', function () {
                    let top = parseInt($(this).scrollTop());
                    if (top > 50) {
                        $(self.header).css({'borderBottom': '1px solid #e7e7e7', 'background': '#fff'});
                        $(self.header).find('span').removeClass('qt-white').addClass('qt-black');
                        $(self.header).find('div').css('color','#000');
                    } else {
                        $(self.header).css({'border':'none', 'background': 'transparent'});
                        $(self.header).find('span').removeClass('qt-black').addClass('qt-white');
                        $(self.header).find('div').css('color','transparent');
                    }
                });

                //查看房间类型
                $(self.body).on("click", ".room-content-div", function(e) {
                    let index = $(this).attr("data-index");
                    if (!$(this).find('.qt-arrow').eq(0).hasClass("qt-checked-arrow")) {

                        $(this).find('.qt-arrow').eq(0).addClass("qt-checked-arrow");
                        //$(this).parent().find('.room-content').removeClass('qt-hide');
                        for (let x in self.settings.dataList[index].RatePlans) {
                            self.settings.dataList[index].RatePlans[x]['BedType'] = self.settings.dataList[index].BedType;
                        }
                        let tpl = document.getElementById("rate_type_tpl").innerHTML;
                        $(this).parent().find('.qt-list').html(doT.template(tpl)(self.settings.dataList[index].RatePlans));
                    } else {
                        //$(this).find('.room-content').addClass('qt-hide');
                        $(this).parent().find('.qt-list').html('');
                        $(this).find('.qt-arrow').eq(0).removeClass("qt-checked-arrow");
                    }
                });

                //预定
                $(self.body).on("click", ".booking", function() {
                    if (!self.isBooking) {
                        $toast('请选择正确的出行日期!');
                        return false;
                    }
                    const roomIndex = $(this).parents('.add-border').find('.room-content-div').data("index");

                    const ratePlansIndex = $(this).data("index");
                    const price = $(this).data("price");
                    // let policyData = $api.strToJson($api.getStorage('trip_policy'));
                    $api.setStorage('card_submit_type', 2);
                    $api.setStorage("checked_rate_plans",JSON.stringify(self.settings.dataList[roomIndex].RatePlans[ratePlansIndex]));

                    let orderType = parseInt(self.settings.hotelPolicy.order_type);
                    if (orderType === 1) {
                        api.openWin({
                            name: 'travel_people_frm',
                            url: '../common/travel_people_frm.html',
                            slidBackEnabled:false
                        });
                    } else {
                        //获取个人的差旅政策
                        self._getSelfPolicy(price,function(data) {
                            self.settings.hotelPolicy = data.data[0];
                            self.settings.hotelPolicy.order_type = orderType;
                            //console.log($api.jsonToStr(self.settings.hotelPolicy));
                            //没有开启申请单 - 正常流程
                            if (orderType === -1) {
                                let dialog = new auiDialog({});
                                dialog.alert({
                                    title: "选择订单类型",
                                    msg: $(".select-travel-type").html(),
                                    buttons: ['取消']
                                }, function(ret) {
                                    //console.log(ret);
                                });
                                $('.policy').html("差旅政策：" + self.settings.hotelPolicy.policy_details);
                                //console.log($api.jsonToStr(self.settings.hotelPolicy));
                                $api.setStorage("trip_policy", JSON.stringify(self.settings.hotelPolicy));
                            } else {
                                //因私
                                if (orderType === 1) {
                                    api.openWin({
                                        name: 'travel_people_frm',
                                        url: '../common/travel_people_frm.html',
                                        slidBackEnabled:false
                                    });
                                } else if(orderType === 3) {
                                    //因公为他人
                                    api.openWin({
                                        name: 'travel_policy_win',
                                        url: '../common/travel_policy_win.html',
                                        pageParam : {
                                            city : self.settings.hotelData.city_name,
                                            price : price
                                        }
                                    });
                                } else {
                                    //因公为自己
                                    let is_violation = self.settings.hotelPolicy.is_violation;
                                    $api.setStorage('is_violation', is_violation);
                                    let violation_reservation = self.settings.hotelPolicy.violation_reservation;
                                    if (is_violation === 'true' && parseInt(violation_reservation) === 0) {
                                        $toast("当前政策标准违规,不允许违规预定");
                                        return false;
                                    }
                                    $api.setStorage('trip_policy', JSON.stringify(self.settings.hotelPolicy));
                                    api.openWin({
                                        name: 'submit_order_win',
                                        url: './submit_order_frm.html',
                                        slidBackEnabled:false
                                    });
                                }
                            }
                        });
                    }
                });

                //查看酒店图片页面
                $(self.body).on("click",".hd-banner.room", function(){
                    api.openWin({
                        name: 'images_win',
                        url: './images_win.html',
                        slidBackEnabled:false
                    });
                });

                //查看酒店地图定位页面
                $(self.body).on("click",".qt-map-location div", function(){
                    api.openWin({
                        name: 'map_win',
                        url: './map_win.html',
                        slidBackEnabled:false
                    });
                });

                //查看酒店详情页面
                $(self.body).on("click",".qt-info-bottom .look-detail,.qt-info-top", function(){
                    api.openWin({
                        name: 'detail_win',
                        url: './detail_win.html',
                        slidBackEnabled:false
                    });
                });

                //变更规则
                $(self.body).on("click",'.change-rule',function(){
                    let dialog = new auiDialog({});
                    let _this = $(this);
                    let str = "<div style='padding:10px;'>"+ _this.attr('data-changeRule') +"</div>";
                    dialog.alert({
                        title: "取消规则",
                        msg: str,
                        buttons: ['确定']
                    });
                });

                $(self.main).find('.qt-bottom-right p').eq(1).click(function () {
                    callTel(self.settings.dataList[0].Detail.Phone);
                });

                $(self.body).on('click', '.aui-dialog-body ul li', function () {
                    let type = $(this).data('type');
                    // console.log(type);
                    self._travelMethod(parseInt(type));
                });
            },
            //获取内容
            getInfo: function () {
                let self = this;
                let request = {};
                request.url = Config.hotel.getRoomItem;
                request.data = {
                    hotel_id: self.settings.hotelData.hotel_id,
                    arrival_date: self.settings.hotelData.arrival_date,
                    departure_date: self.settings.hotelData.departure_date
                };
                ajax(request, function(ret) {
                    if (ret.code === 1) {
                        self.settings.dataList = ret.data;
                        // console.log(JSON.stringify(self.settings.dataList));
                        $api.setStorage("checked_room_detail",JSON.stringify(self.settings.dataList[0].Detail));

                        $(".hd-banner img").attr("src", self.settings.dataList[0].Detail.coverImage);

                        $(self.main).find('.qt-info-top p').eq(0).text(self.settings.dataList[0].Detail.HotelName);

                        $(self.main).find('.qt-bottom-right .look-detail').html(self.settings.dataList[0].Detail.Address);

                        $(self.main).find('.qt-bottom-left .p').eq(0).html(self.settings.dataList[0].Detail.score + '<em class="qt-font12">分</em>');

                        $(self.main).find('.qt-bottom-left .p').eq(1).html(self.settings.dataList[0].Detail.ScoreTxt);

                        $(self.main).find('.qt-bottom-right p').eq(1).find('span').html('酒店电话: ' + self.settings.dataList[0].Detail.Phone);

                        $(self.main).parent().find('.qt-map-location div').html(self.settings.hotelData.city_name + "," + self.settings.dataList[0].Detail.DistrictName + " | " + self.settings.dataList[0].Detail.BusinessZoneName);

                        let tpl = document.getElementById("room_list_tpl").innerHTML;

                        $(self.ellist).html(doT.template(tpl)(self.settings.dataList));

                        $('.room-content-div').eq(0).click();
                    } else {
                        $toast(ret.msg);
                    }
                });
            },
            //正常流程 - 选择出行方式
            _travelMethod: function (type) {
                let self = this;
                self.settings.hotelPolicy.order_self = type;
                $api.setStorage("trip_policy",JSON.stringify(self.settings.hotelPolicy));
                if (type === 2) {
                    let is_violation = self.settings.hotelPolicy.is_violation;
                    $api.setStorage('is_violation', is_violation);
                    let violation_reservation = self.settings.hotelPolicy.violation_reservation;
                    if (is_violation && Number(violation_reservation) === 0) {
                        $toast("当前政策标准违规,不允许违规预定");
                        return false;
                    }
                    $api.setStorage("travel_people", $api.getStorage("user_id"));
                    // $api.setStorage("trip_policy",JSON.stringify(policy));
                    api.openWin({
                        name: 'submit_order_win',
                        url: './submit_order_frm.html'
                    });
                } else {
                    //因公为他人
                    api.openWin({
                        name: 'travel_people_win',
                        url: '../common/travel_people_frm.html'
                    });
                }
            },
            /**
             *
             * @param price
             * @param callback
             * @private
             */
            _getSelfPolicy: function (price, callback) {
                let self = this;
                //获取个人的差旅政策
                let param = {};
                param.url = Config.hotel.getHotelPolicy;
                param.data = {
                    city: self.settings.hotelData.city_name,
                    price: price,
                    userIds: $api.getStorage('user_id')
                };
                ajax(param, function(data) {
                    // console.log($api.jsonToStr(data));
                    if (data.code === 1) {
                        callback(data);
                    } else{
                        $toast(data.msg);
                    }
                });
            },
            //获取星期几
            _getWeekNum: function(beginDate, endDate) {
                let self = this;
                let nowDate = new Date();
                var tomorrow = self._addDate(nowDate,1);
                var aftertomorrow = self._addDate(nowDate,2);
                var myweek = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
                var st = new Date(beginDate);
                var en = new Date(endDate);
                let curWeek = myweek[st.getDay()];
                let curWeek1 = myweek[en.getDay()];

                if(st.getDay() === nowDate.getDay() && st.getDate() === nowDate.getDate() && nowDate.getMonth() === st.getMonth()){
                    curWeek = '今天';
                } else if(st.getDay() === tomorrow.getDay() && st.getDate() === tomorrow.getDate() && tomorrow.getMonth() === st.getMonth()){
                    curWeek = '明天';
                } else if(st.getDay() === aftertomorrow.getDay() && st.getDate() === aftertomorrow.getDate() && aftertomorrow.getMonth() === st.getMonth()) {
                    curWeek = '后天';
                }

                if(en.getDay() === nowDate.getDay() && en.getDate() === nowDate.getDate() && nowDate.getMonth() === en.getMonth()){
                    curWeek1 = '今天';
                } else if(en.getDay() === tomorrow.getDay() && en.getDate() === tomorrow.getDate() && tomorrow.getMonth() === en.getMonth()){
                    curWeek1 = '明天';
                } else if(en.getDay() === aftertomorrow.getDay() && en.getDate() === aftertomorrow.getDate() && aftertomorrow.getMonth() === en.getMonth()) {
                    curWeek1 = '后天';
                }
                return [curWeek+'入住', curWeek1+'离店'];
            },
            _addDate: function (date,days) {
                let me = this;
                var d = new Date(date);
                d.setDate(d.getDate()+days);
                var m = d.getMonth()+1;
                var strTime =  d.getFullYear()+'-'+m+'-'+d.getDate();
                return me.changeType(strTime);
            },
            /*时间格式化为Date*/
            changeType: function (strTime) {
                return new Date(Date.parse(strTime.replace(/-/g,  "/")));
            }
        };
        return detail;
    })();
    $.fn.extend = {
        selectors: {
            header: "#header"
            ,body: 'body'
            ,mainInfo: '.qt-main-info'
            ,elList: '.qt-list.room-list'
            ,arrival: "#startDate"
            ,departure: "#endDate"
        }
        //基本参数
        ,hotelData: JSON.parse($api.getStorage('hotel_data'))
        ,hotelPolicy: JSON.parse($api.getStorage('trip_policy'))
        ,dataList: null
    };
    window.detail = detail;
})(jQuery, window);